#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
/*int main()
{
	//1，阻塞式等待(wait)
	pid_t id=fork();
	if(id<0)
	{
		perror("fork");
		exit(1);
	}
	else if(id==0)
	{
			sleep(1);
		printf("child =%d\n",getpid());
		//sleep(3);
		//exit(0);
	}
	else
	{
		int status=0;
		pid_t pid=waitpid(-1,&status,0);
		if(WIFEXITED(status)&&pid==id)
		{
			printf("wait child 5s success the child id==%d\n",WEXITSTATUS(status));
		}
		else
		{
			printf("wait child failded\n");
			return 1;
		}
		return 0;
		exit(1);
	}
}*/
int main()
{
	//2.非阻塞式等待(waitpid)
	pid_t id=fork();
	if(id<0)
	{
		perror("fork");
		exit(1);
	}
	else if(id==0)
	{
		printf("child =%d\n",getpid());
		sleep(100);
		exit(200);
	}
	else
	{
		int status=0;
		pid_t pid=0;
		do
		{
		     pid=waitpid(-1,&status,WNOHANG);
			if(pid==0)
			{
				printf("wait child now!!\n");
			}
			sleep(1);
			
		}while(pid==0);
		if(WIFEXITED(status)&&pid==id)
		{
			printf("wait child 5s success the child id==%d\n",WEXITSTATUS(status));
		}
		else
		{
			printf("wait child failded id=%d\n",WEXITSTATUS(status));
			return 1;
		}
		return 0;
		exit(1);
	}
}
